package com.wl156.activities;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.model.WebServiceClient;
import com.wl156.utils.Utils;

public class Login extends Activity implements OnClickListener {

	private EditText mUsername;
	private EditText mPassword;
	private WebServiceClient mWebServiceClient;
	private CheckBox mRememberPassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Window win = getWindow();
		// win.requestFeature(Window.FEATURE_LEFT_ICON);
		setContentView(R.layout.act_login);
		// win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
		// R.drawable.ic_launcher);

		mWebServiceClient = new WebServiceClient(this);

		Button login = (Button) findViewById(R.id.login);
		login.setOnClickListener(this);
		Button register = (Button) findViewById(R.id.register);
		register.setOnClickListener(this);
		Button help = (Button) findViewById(R.id.help);
		help.setOnClickListener(this);
		findViewById(R.id.pwd_reset).setOnClickListener(this);

		mRememberPassword = (CheckBox) findViewById(R.id.rememberPassword);
		mRememberPassword
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						SharedPreferences setup = getSharedPreferences("setup",
								MODE_PRIVATE);
						setup.edit().putBoolean("rememberPassword", isChecked)
								.commit();
					}
				});

		mUsername = (EditText) findViewById(R.id.username);
		mPassword = (EditText) findViewById(R.id.password);

		// XXX: FOR DEBUG REMOVE IT
		mUsername.setText("");
		mPassword.setText("");

		SharedPreferences setup = getSharedPreferences("setup", MODE_PRIVATE);
		boolean rp = setup.getBoolean("rememberPassword", false);
		mRememberPassword.setChecked(rp);

		String userName = ((MyApp) getApplication()).getUserIdFromXml();
		if (!TextUtils.isEmpty(userName)) {
			mUsername.setText(userName);

			String pass = setup.getString("p", "");
			mPassword.setText(pass);
		}
		
		if(getIntent().getExtras() != null) {
			String username = getIntent().getStringExtra("username");
			String password = getIntent().getStringExtra("password");
			mUsername.setText(username);
			mPassword.setText(password);
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.pwd_reset: {
			Intent i = new Intent(this, InputPassword.class);
			startActivity(i);
		}
			break;
		case R.id.login:
			final String username = mUsername.getText().toString();
			final String password = mPassword.getText().toString();

			SharedPreferences setup = getSharedPreferences("setup",
					MODE_PRIVATE);
			boolean rp = setup.getBoolean("rememberPassword", false);
			if (rp) {
				setup.edit().putString("p", password).commit();
			}

			new AsyncTask<Void, Void, Object>() {
				ProgressDialog mDialog;

				@Override
				protected void onPreExecute() {
					mDialog = ProgressDialog.show(Login.this, "", "登录中");
				};

				@Override
				protected void onPostExecute(Object result) {

					mDialog.dismiss();

					if (result instanceof Exception) {
						Exception e = (Exception) result;

						Toast.makeText(Login.this, "网络连接异常，请稍后再试",
								Toast.LENGTH_LONG).show();
					} else {
						String token = null;
						String type = null;
						String error = null;
						if (result instanceof SoapObject) {
							SoapObject so = (SoapObject) result;
							if (so.getPropertyCount() == 1) {
								Toast.makeText(
										Login.this,
										Utils.propertyToShow(so.getProperty(0)),
										Toast.LENGTH_LONG).show();
								return;
							} else {
								token = so.getProperty(0).toString();
								type = so.getProperty(1).toString();
							}
						} else if (result instanceof SoapPrimitive) {
							SoapPrimitive sp = (SoapPrimitive) result;
							error = sp.toString();
							Toast.makeText(Login.this, error, Toast.LENGTH_LONG)
									.show();
						}

						((MyApp) getApplication()).login(username, token, type);
						startActivity(new Intent(Login.this, MainTab.class));
						finish();
					}
				};

				@Override
				protected Object doInBackground(Void... params) {
					try {
						return mWebServiceClient.login(username, password);
					} catch (IOException e) {
						e.printStackTrace();
						return e;
					} catch (XmlPullParserException e) {
						e.printStackTrace();
						return e;
					}
				}

			}.execute();

			break;
		case R.id.register:
			startActivity(new Intent(this, Register.class));
			break;
		case R.id.help:
			AlertDialog.Builder builder = new Builder(this);
			builder.setTitle("注册说明");
			builder.setMessage("欢迎使用156物流Android客户端");
			builder.setNegativeButton("知道了", null);
			builder.show();
			break;
		}
	}
}
